<template>
  <div class="register-container">
    <div class="container">
      <!-- 左侧图标占位 -->
      <div class="logo-placeholder">
        <div class="icon-box">
          <img src="@/assets/Logo.png" alt="Logo" />
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="form-container">
        <!-- 标题 + 返回按钮同行 -->
        <div class="title-with-back">
          <h2 class="title">用户注册</h2>
          <router-link to="/user-login" class="back-to-login">返回登录</router-link>
        </div>

        <!-- 表单内容 -->
        <div class="form-item">
          <label for="userName" class="label">用户名</label>
          <input id="userName" v-model="formData.userName" type="text" placeholder="请输入用户名" class="input-field" />
        </div>

        <div class="form-item">
          <label for="phone" class="label">手机号</label>
          <input id="phone" v-model="formData.phone" type="tel" placeholder="请输入手机号" class="input-field" />
        </div>

        <div class="form-item">
          <label for="password" class="label">密码</label>
          <input id="password" v-model="formData.password" type="password" placeholder="请输入你的密码" class="input-field" />
        </div>

        <button class="submit-btn" @click="handleRegister" :disabled="isLoading">
          {{ isLoading ? '注册中...' : '同意并注册' }}
        </button>

        <div class="agreement">
          <input id="agreement" v-model="formData.agree" type="checkbox" class="checkbox" />
          <label for="agreement" class="agreement-text">
            已阅读并同意鲸选平台的各项协议
          </label>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { register } from '@/api';

const router = useRouter();
const isLoading = ref(false);

// 表单数据
const formData = ref({
  userName: '',
  phone: '',
  password: '',
  agree: false
});

// 注册处理函数
const handleRegister = async () => {
  if (!formData.value.userName.trim()) {
    alert('请输入用户名');
    return;
  }
  if (!formData.value.phone.trim()) {
    alert('请输入手机号');
    return;
  }
  // 简单手机号校验
  if (!/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    alert('请输入正确的手机号');
    return;
  }
  if (!formData.value.password) {
    alert('请输入密码');
    return;
  }
  if (!formData.value.agree) {
    alert('请先同意协议');
    return;
  }

  try {
    isLoading.value = true;
    console.log('注册信息:', formData.value);
    
    // 调用 API 提交注册
    // 构造后端需要的 UserRegisterRequest 对象
    const requestData = {
      userName: formData.value.userName,
      phone: formData.value.phone,
      password: formData.value.password
    };
    
    await register(requestData);
    
    alert('注册成功！请登录');
    router.push('/user-login');
  } catch (error) {
    console.error('注册失败:', error);
    alert(error.message || '注册失败，请稍后重试');
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
@import '@/CSS/Registration.css';
</style>